package com.malou.client.ventas.venta;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.AggregationRenderer;
import com.extjs.gxt.ui.client.widget.grid.AggregationRowConfig;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.RowNumberer;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Frame;
import com.malou.client.MalouConstants;
import com.malou.client.reportes.ReporteService;
import com.malou.client.reportes.ReporteServiceAsync;
import com.malou.client.util.Utilities;
import com.malou.client.ventas.cliente.Clientes;
import com.malou.client.ventas.modeloprenda.ModeloPrendas;
import com.malou.client.ventas.serie.Series;

public class VentaDialog extends Dialog {
	private TextField<String> dni_ruc;
	public HiddenField<String> cliente_id;
	private Frame frame;
	public ComboBox<BeanModel> nombreapellido;
	private ComboBox<BeanModel> documento;
	private Button guardar;
	private Button cancelar;
	public Status status;
	private MalouConstants constants = GWT.create(MalouConstants.class);

	public TextField<String> codigo;
	public HiddenField<String> prenda_id;
	public ComboBox<BeanModel> prenda;
	public NumberField preciounitario;
	public NumberField cantidadNumberField;
	public NumberField stock;
	private Button addDetalle;
	private Button delDetalle;

	private AggregationRowConfig<BeanModel> total;
	private AggregationRowConfig<BeanModel> subtotal;
	private AggregationRowConfig<BeanModel> igv;

	private Double igv_value = 1.00;
	private ListStore<BeanModel> store;
	private EditorGrid<BeanModel> grid;
	private ToolBar toolBar;
	private Boolean control = false;
	private FieldSet clienteFieldSet;
	private FieldSet documentoFieldSet;
	private FieldSet prendaFieldSet;
	private FormPanel formpanel;
	private ContentPanel gridPanel;
	private LayoutContainer lc_reporte;
	
	

	public VentaDialog() {
		super();
		setModal(true);
		setSize(995, 558);
		setButtons("");
		setResizable(false);
		setIconStyle("icon-stock");
		setHeading(constants.ventaNuevo());
		
		toolBar = new ToolBar();
		
		formpanel = new FormPanel();
		formpanel.setBodyBorder(false);
		formpanel.setBodyBorder(false);
		formpanel.setHeaderVisible(false);
		
		clienteFieldSet = new FieldSet();
		clienteFieldSet.setHeading(constants.ventaClienteData());
		clienteFieldSet.setStyleAttribute("padding", "8px");
		clienteFieldSet.setLayout(new ColumnLayout());
		
		documentoFieldSet = new FieldSet();
		documentoFieldSet.setHeading(constants.ventaTipoVenta());
		documentoFieldSet.setStyleAttribute("padding", "8px");
				
		prendaFieldSet = new FieldSet();
		prendaFieldSet.setHeading(constants.ventaAgregarDetalle());
		prendaFieldSet.setStyleAttribute("padding", "8px");
		prendaFieldSet.setLayout(new ColumnLayout());
		
		lc_reporte=new LayoutContainer();
		lc_reporte.setLayout(new FitLayout());
		lc_reporte.setHeight(330);
		
		addListener(Events.Show,new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
			clearPrincipal();
			}
		});
		
		 

		addFields();
		setFocusWidget(dni_ruc);
		
	}

	private void addFields() {
		Clientes.ventaDialog = this;
		ModeloPrendas.ventaDialog = this;
		Series.getComboDocumento();
		Series.loaderCombo.load(); 

		documento = new ComboBox<BeanModel>();
		documento.setEditable(false);
		documento.setFieldLabel(constants.ventaDocumentoVenta());

		documento.setDisplayField("descripcion");
		documento.setEmptyText(constants.seleccione());
		documento.setStore(Series.storeCombo);
		documento.setTypeAhead(true);
		documento.setTriggerAction(TriggerAction.ALL);
		documento.setValueField("descripcion");
		documento.getStore().addStoreListener(new StoreListener<BeanModel>() {
			public void storeDataChanged(StoreEvent<BeanModel> se) {
				super.storeDataChanged(se);
				List<BeanModel> list = new ArrayList<BeanModel>();
				list.add(documento.getStore().getAt(2));// documento: otro
				documento.setSelection(list);
			}
		});
		documento
				.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {

					@Override
					public void selectionChanged(
							SelectionChangedEvent<BeanModel> se) {
					
						if (se.getSelectedItem().get("id").toString()
								.equals("2")) {
							igv_value = Utilities.igv_value;
							dni_ruc.setAllowBlank(false);
						} else {
							igv_value = 1.00;
							dni_ruc.setAllowBlank(true);
						}
						grid.getView().refresh(false);

					}
				});
		

		cliente_id = new HiddenField<String>();
		
		dni_ruc = new TextField<String>();
		dni_ruc.setFieldLabel("DNI / RUC");
		dni_ruc.setMinLength(8);
		dni_ruc.setMaxLength(11);
		dni_ruc.addKeyListener(new KeyListener() {
			public void componentKeyDown(ComponentEvent event) {
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					if (Utilities.hasValue(dni_ruc)) {
						Clientes.getCliente(dni_ruc.getValue().toString());
					}
				 if(dni_ruc.getValue()==null)	
					 nombreapellido.focus();
				 else
					 codigo.focus();
				}
			}
		});

	
		Clientes.autoComplete();

		nombreapellido = new ComboBox<BeanModel>();
		nombreapellido.setFieldLabel(constants.ClienteNombreApellido());
		nombreapellido.setDisplayField("cliente");
		nombreapellido.setStore(Clientes.storeAutocomplete);
		nombreapellido.setValueField("cliente");
		nombreapellido.setPageSize(10);
		nombreapellido.setTriggerAction(TriggerAction.ALL);
		nombreapellido.setUseQueryCache(false);
		nombreapellido
				.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {

					@Override
					public void selectionChanged(
							SelectionChangedEvent<BeanModel> se) {
						if (se.getSelectedItem() != null) {
							if (se.getSelectedItem().get("dni") != null)
								dni_ruc.setValue(se.getSelectedItem()
										.get("dni").toString());
							else
								dni_ruc.setValue(se.getSelectedItem()
										.get("ruc").toString());
							cliente_id.setValue(se.getSelectedItem().get("id")
									.toString());
						}
					}
				});

		nombreapellido.addKeyListener(new KeyListener() {
			public void componentKeyDown(ComponentEvent event) {
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
						codigo.focus();
				}
			}
		});

		prenda_id = new HiddenField<String>();
		formpanel.add(prenda_id);
		

		
		codigo = new TextField<String>();
		codigo.setFieldLabel(constants.ventaCodigo());
		codigo.addKeyListener(new KeyListener() {

			public void componentKeyDown(ComponentEvent event) {
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					if (codigo.getValue() != null) {
						ModeloPrendas.getPrenda(codigo.getValue());
					}
					else 
						prenda.focus();
				}
			}
		});

		ModeloPrendas.autoComplete();

		prenda = new ComboBox<BeanModel>();
		prenda.setFieldLabel(constants.ventaPrenda());
		prenda.setDisplayField("prenda");
		prenda.setStore(ModeloPrendas.storeAutocomplete);
		prenda.setValueField("id");
		prenda.setPageSize(10);
		prenda.setTriggerAction(TriggerAction.ALL);
		prenda.setUseQueryCache(false);
		prenda.setHideTrigger(true);
		prenda.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {
			@Override
			public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
				if (se.getSelectedItem() != null) {
					codigo.setValue(se.getSelectedItem().get("codigo")
							.toString());
					prenda_id.setValue(se.getSelectedItem().get("id")
							.toString());
					preciounitario.setValue(Double.valueOf(se.getSelectedItem()
							.get("precioventa").toString()));

					stock.setValue(Integer.valueOf(se.getSelectedItem()
							.get("stock").toString()));
					preciounitario.focus();
					cantidadNumberField.setValue(1);
					
					cantidadNumberField.focus();
					
				}
			}
		});

		preciounitario = new NumberField();
		preciounitario.setFieldLabel(constants.ventaPrecio());
		preciounitario.setAllowNegative(false);
		preciounitario.setFormat(NumberFormat.getFormat("0.00"));
		preciounitario.setMinValue(1.00);
		preciounitario.setSelectOnFocus(true);
		preciounitario.addKeyListener(new KeyListener() {

			public void componentKeyDown(ComponentEvent event) {
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					cantidadNumberField.focus();
				}
			}
		});
	
		cantidadNumberField = new NumberField();
		cantidadNumberField.setFieldLabel(constants.ventaCantidadData());
		cantidadNumberField.setAllowNegative(false);
		cantidadNumberField.setAllowDecimals(false);
		cantidadNumberField.setPropertyEditorType(Integer.class);
		cantidadNumberField.setMinValue(1);
		cantidadNumberField.addKeyListener(new KeyListener() {

			public void componentKeyDown(ComponentEvent event) {
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					agregarDetalle();
				}
			}
		});
		
		stock = new NumberField();
		stock.setReadOnly(true);
		stock.setFieldLabel("Stock");
		stock.setPropertyEditorType(Integer.class);
		
		addDetalle = new Button(constants.ventaAgregar(),IconHelper.createPath("images/icons/new.gif"));
		addDetalle.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				agregarDetalle();
			}
		});
		
		delDetalle = new Button(constants.eliminar(),IconHelper.createPath("images/icons/delete.gif"));
		delDetalle.setEnabled(false);
		delDetalle.addSelectionListener(new SelectionListener<ButtonEvent>() {
		@Override
			public void componentSelected(ButtonEvent ce) {
				BeanModel be = grid.getSelectionModel().getSelectedItem();
				grid.getStore().remove(be);
			}
		});

		toolBar.add(delDetalle);
		

		store = new ListStore<BeanModel>();
		store.addStoreListener(new StoreListener<BeanModel>() {
			public void storeUpdate(StoreEvent<BeanModel> se) {
				Double precio = (Double) se.getRecord().get("preciounitario");
				Integer cantidad = (Integer) se.getRecord().get("cantidad");
				se.getRecord().set("subtotal", precio * cantidad);
				store.commitChanges();
			}
		});

		RowNumberer r = new RowNumberer();
		ArrayList<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		ColumnConfig column = new ColumnConfig();
		columns.add(r);
		columns.add(new ColumnConfig("codigo", constants.ventaCodigoPrenda(),110));
		columns.add(new ColumnConfig("modeloprenda", constants.ventaModeloPrenda(), 450));
		column = new ColumnConfig("preciounitario", constants.ventaCosto(), 100);
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setNumberFormat(NumberFormat.getFormat("0.00"));

		NumberField precio = new NumberField();
		precio.setAllowBlank(false);
		precio.setPropertyEditorType(Double.class);
		precio.setAllowNegative(false);
		precio.setFormat(NumberFormat.getFormat("0.00"));

		column.setEditor(new CellEditor(precio));
		columns.add(column);

		column = new ColumnConfig("descuento", constants.ventaDescuento(), 100);
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setNumberFormat(NumberFormat.getFormat("0.00"));
		columns.add(column);

		column = new ColumnConfig("cantidad", constants.ventaCantidad(), 80);
		column.setAlignment(HorizontalAlignment.RIGHT);

		NumberField cantidad = new NumberField();
		cantidad.setAllowBlank(false);
		cantidad.setPropertyEditorType(Integer.class);
		cantidad.setAllowNegative(false);
		cantidad.setAllowDecimals(false);

		column.setEditor(new CellEditor(cantidad));
		columns.add(column);

		column = new ColumnConfig("subtotal", constants.ventaSubtotal(), 80);
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setNumberFormat(NumberFormat.getFormat("0.00"));
		columns.add(column);

		ColumnModel cm = new ColumnModel(columns);

		subtotal = new AggregationRowConfig<BeanModel>();
		subtotal.setHtml("cantidad", constants.ventaSubtotalResumen());

		subtotal.setSummaryType("subtotal", SummaryType.SUM);
		subtotal.setRenderer("subtotal", new AggregationRenderer<BeanModel>() {
			public Object render(Number value, int colIndex,
					Grid<BeanModel> grid, ListStore<BeanModel> store) {

				if (value != null)
					return NumberFormat.getFormat("0.00").format(
							value.doubleValue() / igv_value);
				else
					return "";
			}
		});

		cm.addAggregationRow(subtotal);

		igv = new AggregationRowConfig<BeanModel>();
		igv.setHtml("cantidad", constants.ventaIgv());

		igv.setSummaryType("subtotal", SummaryType.SUM);

		igv.setRenderer("subtotal", new AggregationRenderer<BeanModel>() {
			public Object render(Number value, int colIndex,
					Grid<BeanModel> grid, ListStore<BeanModel> store) {

				if (value != null)
					return NumberFormat.getFormat("0.00").format(
							value.doubleValue() - value.doubleValue()
									/ igv_value);
				else
					return "";
			}
		});
		cm.addAggregationRow(igv);

		total = new AggregationRowConfig<BeanModel>();
		total.setHtml("cantidad", constants.ventaTotalResumen());

		total.setSummaryType("subtotal", SummaryType.SUM);
		total.setSummaryFormat("subtotal", NumberFormat.getFormat("0.00"));

		cm.addAggregationRow(total);

		grid = new EditorGrid<BeanModel>(store, cm);
		grid.addPlugin(r);
		grid.setSelectionModel(new GridSelectionModel<BeanModel>());
		grid.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {

					@Override
					public void handleEvent(SelectionChangedEvent<BeanModel> be) {
						if (be.getSelectedItem() != null)
							delDetalle.setEnabled(true);
						else
							delDetalle.setEnabled(false);
					}
				});

		gridPanel = new ContentPanel();
		gridPanel.setHeaderVisible(false);
		gridPanel.setLayout(new FitLayout());
		gridPanel.setHeight(330);
		gridPanel.add(grid);
		gridPanel.setTopComponent(toolBar);
		
		
		clienteFieldSet.add(setLayout(dni_ruc, "95%", 60),	new ColumnData(0.30));
		clienteFieldSet.add(setLayout(nombreapellido, "100%", 70),new ColumnData(0.70));
		
		documentoFieldSet.add(setLayout(documento, "100%", 70),	new ColumnData(1));
		
		prendaFieldSet.add(setLayout(codigo, "95%", 40),new ColumnData(.18));
		prendaFieldSet.add(setLayout(prenda, "95%", 40),new ColumnData(.35));
		prendaFieldSet.add(setLayout(stock, "95%", 38),new ColumnData(.10));
		prendaFieldSet.add(setLayout(preciounitario, "95%", 60),new ColumnData(.15));
		prendaFieldSet.add(setLayout(cantidadNumberField, "90%", 50),new ColumnData(.15));
		prendaFieldSet.add(addDetalle,new ColumnData(.07));
		
		LayoutContainer encabezado=new LayoutContainer();
		encabezado.setLayout(new ColumnLayout());
		
		encabezado.add(setLayout(clienteFieldSet, "95%", 0),new ColumnData(.7));
		encabezado.add(setLayout(documentoFieldSet, "100%", 0),new ColumnData(.3));
		
		lc_reporte.add(gridPanel);
		
		formpanel.add(encabezado);
		formpanel.add(prendaFieldSet);
		formpanel.add(lc_reporte);
		
		add(formpanel);
		
	}

	@Override
	protected void createButtons() {
		super.createButtons();

		if (constants == null) {
			constants = GWT.create(MalouConstants.class);
		}

		status = new Status();
		status.setBusy(constants.guardando());
		status.hide();
		status.setAutoWidth(true);
		getButtonBar().add(status);

		getButtonBar().add(new FillToolItem());

		cancelar = new Button(constants.limpiar(),
				IconHelper.createPath("images/icons/cancel.png"));
		cancelar.setSize(70, 25);
		
		cancelar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				
				
				if(control){
					lc_reporte.removeAll();
					lc_reporte.add(gridPanel);
					lc_reporte.layout();
					guardar.setVisible(true);
					control=false;
					
				}
				clearPrincipal();
				
			}

		});

		guardar = new Button(constants.guardar(),
				IconHelper.createPath("images/icons/save_all.png"));
		guardar.setSize(70, 25);


		guardar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				if (validarPrincipal()) {
					status.show();
					getButtonBar().disable();
					Venta v = new Venta();
					if (cliente_id.getValue() != null)
						v.setCliente_id(Integer.valueOf(cliente_id.getValue()));
					if (documento.getValue().get("id") != null)
						v.setTipodocumento_id(Integer.parseInt(documento
								.getValue().get("id").toString()));

					List<DetalleVenta> list = new ArrayList<DetalleVenta>();
					DetalleVenta dv;
					Double monto;
					Double precio;
					Integer cant;
					Double total = 0.00;
					for (BeanModel b : store.getModels()) {
						dv = new DetalleVenta();
						dv.setModeloprenda_id(Integer.valueOf(b.get(
								"modeloprenda_id").toString()));
						dv.setModeloprenda(b.get("modeloprenda").toString());
						precio = Double.valueOf(b.get("preciounitario")
								.toString());
						dv.setPreciounitario(precio);
						cant = Integer.valueOf(b.get("cantidad").toString());
						dv.setCantidad(cant);
						monto = precio * cant;
						dv.setSubtotal(monto);
						list.add(dv);

						total += monto;
					}
					v.setTotal(total);
					v.setIgv(total - total / igv_value);
					v.setFecha(new Date());

					Ventas.ventaDialog = VentaDialog.this;
					Ventas.save(v, list);
				}
			}
		});

		addButton(guardar);
		addButton(cancelar);

	}

	public boolean validarDetalle() {
		codigo.setAllowBlank(false);
		prenda.setAllowBlank(false);
		preciounitario.setAllowBlank(false);
		cantidadNumberField.setAllowBlank(false);

		boolean cod = codigo.isValid();
		boolean pre = prenda.isValid();
		boolean preunit = preciounitario.isValid();
		boolean cant = cantidadNumberField.isValid();
		boolean stockDisponible = true;
		boolean stockSuficiente = true;
		if (cod && pre && preunit && cant) {
			Integer st = Integer.valueOf(stock.getValue().toString());
			if (st == 0) {
				stockDisponible = false;
				MessageBox.alert(constants.sistemaMarcocruzado(),
						constants.ventaNoExistePrenda(), null);
			} else if (cant) {
				Integer stCant = Integer
						.valueOf(cantidadNumberField.getValue().toString());
				if (stCant > st) {
					stockSuficiente = false;
					MessageBox.alert(constants.sistemaMarcocruzado(),
							constants.ventaNoStock(), null);
				}
			}
		}

		codigo.setAllowBlank(true);
		prenda.setAllowBlank(true);
		preciounitario.setAllowBlank(true);
		cantidadNumberField.setAllowBlank(true);

		return cod && pre && preunit && cant && stockDisponible
				&& stockSuficiente;
	}

	public boolean validarPrincipal() {
		boolean dr = dni_ruc.isValid();
		boolean det = true;
		if (store.getCount() == 0) {
			det = false;
			MessageBox.alert(constants.sistemaMarcocruzado(),
					constants.ventaDetalleRequerido(), null);
			codigo.focus();
		}
		if (!dr)
			dni_ruc.focus();
		return dr && det;
	}

	public void clearDetalle() {

		codigo.clear();
		prenda.clear();
		preciounitario.clear();
		cantidadNumberField.clear();
		stock.clear();

	}

	public void clearPrincipal() {

		dni_ruc.clear();
		dni_ruc.focus();
		nombreapellido.clear();
		store.removeAll();
		clearDetalle();
		List<BeanModel> list = new ArrayList<BeanModel>();
		list.add(documento.getStore().getAt(2));// documento: otro
		documento.setSelection(list);

	}

	public void agregarDetalle() {
		if (validarDetalle()) {

			Boolean add = true;
			if (store.getCount() > 0) {
				String mp_id = prenda_id.getValue();
				Double precio_unit = Double.valueOf(preciounitario.getValue()
						.toString());
				Integer cant = Integer.valueOf(cantidadNumberField.getValue().toString());
				Integer st = Integer.valueOf(stock.getValue().toString());

				Integer mpdetalle_id;
				Integer cantdetalle;
				for (BeanModel b : store.getModels()) {
					mpdetalle_id = b.get("modeloprenda_id");

					if (mpdetalle_id.toString().equals(mp_id)) {
						add = false;
						cantdetalle = b.get("cantidad");
						if (cantdetalle + cant <= st) {
							store.getRecord(b).set("preciounitario",
									precio_unit);
							store.getRecord(b).set("cantidad",
									cantdetalle + cant);
							store.getRecord(b).set("subtotal",
									precio_unit * (cantdetalle + cant));
							store.commitChanges();
							clearDetalle();
							codigo.focus();
						} else {
							MessageBox.alert(constants.sistemaMarcocruzado(),
									constants.ventaNoStock(), null);
						}
						break;
					}
				}

			}
			if (add) {
				DetalleVenta dv = new DetalleVenta();
				dv.setModeloprenda_id(Integer.valueOf(prenda_id.getValue()));
				dv.setModeloprenda(prenda.getRawValue());
				dv.setCodigo(codigo.getValue());
				Double precio = Double.valueOf(preciounitario.getValue()
						.toString());
				Integer cant = Integer.valueOf(cantidadNumberField.getValue().toString());
				Double monto = precio * cant;
				dv.setPreciounitario(precio);
				dv.setCantidad(cant);
				dv.setSubtotal(monto);

				BeanModelFactory beanModelFactory = BeanModelLookup.get()
						.getFactory(dv.getClass());
				store.add(beanModelFactory.createModel(dv));
				clearDetalle();
				codigo.focus();
			}
		}
	}


	public void imprimir(Integer venta_id) {

		if (!control) {
			frame = new Frame();
					
			lc_reporte.removeAll();
			lc_reporte.add(frame);
			

			AsyncCallback<String> reportURLCallback = new AsyncCallback<String>() {

				MessageBox messageBox = new MessageBox();

				@Override
				public void onFailure(Throwable caught) {
					messageBox.setMessage(constants.errorConexion());
					messageBox.show();
					caught.printStackTrace();
				}

				@Override
				public void onSuccess(String result) {
					if (result != null) {
						result = result.replace("reports/", "");
						frame.setUrl(GWT.getModuleBaseURL()
								+ "DownloadPDF?name=" + result);
					} else {
						messageBox
								.setMessage(constants.noSePudoCargarReporte());
						messageBox.show();
					}
				}

			};
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("param_venta_id", venta_id);
			((ReporteServiceAsync) GWT.create(ReporteService.class)).createPdf(
					"reports/NotaVenta", param, null, venta_id,
					reportURLCallback);
			lc_reporte.layout();
			control = true;
			guardar.setVisible(false);
		}
	}
	
	 private LayoutContainer setLayout(Component comp, String porcentaje,Integer withlabel) {
			LayoutContainer layout = new LayoutContainer();
			FormLayout fl = new FormLayout(LabelAlign.LEFT);
			fl.setLabelWidth(withlabel);
			layout.setLayout(fl);
			layout.add(comp, new FormData(porcentaje));

			return layout;
	}
	
}
